package problem15;

//15.三数之和
//https://leetcode.cn/problems/3sum/

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        int n = nums.length;
        List<List<Integer>> ret = new ArrayList<>();
        Arrays.sort(nums);
        for(int i=0;i<n;) {
            int left = i+1,right = n-1,target = -nums[i];
            while(left<right) {
                int sum = nums[left]+nums[right];
                if(sum<target) {
                    left++;
                }else if(sum>target) {
                    right--;
                }else {
                    List<Integer> tmp = new ArrayList<>();
                    tmp.add(nums[i]);
                    tmp.add(nums[left]);
                    tmp.add(nums[right]);
                    ret.add(tmp);
                    left++;
                    right--;
                    while(left<right&&nums[left-1]==nums[left]) {
                        left++;
                    }
                    while(left<right&&nums[right+1]==nums[right]) {
                        right--;
                    }
                }
            }
            i++;
            while(i<n&&nums[i-1]==nums[i]) {
                i++;
            }
        }
        return ret;
    }
}